package com.huifeng.dao.impl;

import com.huifeng.bean.Good;
import com.huifeng.dao.GoodDao;
import com.huifeng.utils.PageUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import sun.security.x509.IssuerAlternativeNameExtension;

import java.sql.SQLException;
import java.util.List;

public class GoodDaoimpl implements GoodDao {
    QueryRunner runner= new QueryRunner(new ComboPooledDataSource());
    @Override
    public int findtotalPage() {
        String sql="select count(*) from good";
        int count =0;
        try {
            Object obj = runner.query(sql, new ScalarHandler<>());
            count=Integer.parseInt(obj.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public List<Good> FindByPage(PageUtils pu) {
        String sql="select*from good limit ?,?";
        List<Good> list =null;
        try {
            list = runner.query(sql, new BeanListHandler<>(Good.class), pu.getStartIndex(), pu.getPageSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int insertBook(Good good) {
        String sql="INSERT INTO good(gname,price,unit,descs)VALUES(?,?,?,?)";
       int row =0;
        try {
          row = runner.update(sql,good.getGname(), good.getPrice(), good.getUnit(), good.getDescs());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    @Override
    public Good findByid(int gid) {
        String sql="SELECT * FROM good WHERE gid=?";
        Good good =null;
        try {
            good = runner.query(sql, new BeanHandler<>(Good.class),gid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return good;
    }

    @Override
    public int updateGood(Good good) {
        String  sql="UPDATE good SET gname=?,price=?,unit=?,descs=? WHERE gid=?";
        int row =0;
        try {
            row = runner.update(sql,good.getGname(),good.getPrice(),good.getUnit(),good.getDescs(),good.getGid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    @Override
    public int delectGood(int gid) {
        String sql="DELETE FROM good WHERE gid =?";
        int row =0;
        try {
            row = runner.update(sql,gid);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
}
